/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package data;

/**
 *
 * @author Yang Wang <yang@digitalmenubox.com>
 */
import java.util.HashMap;
import java.util.Map;

import config.Settings;

public abstract class Downloader {
	public static final int DIGITAL_MARKETING_BOX_SERVER = 0;
	public static final int DIGITAL_AUTOBOX_BOX_SERVER = 1;
	public static final int DIGITAL_REAL_ESTATE_BOX_SERVER = 2;
	public static final int DIGITAL_REAL_ESTATE_BOX_AGENT_SERVER = 3;

	public static final String HTTP_SERVER_ROOT_0 = "http://www.digitalmarketingbox.com/webtool/boxdata/";
	public static final String HTTP_SERVER_ROOT_1 = "http://www.digitalautobox.com/";
	public static final String HTTP_SERVER_ROOT_2 = "http://www.digitalrealestatebox.com/";
	public static final String HTTP_SERVER_ROOT_3 = "http://www.digitalmarketingbox.com/webtool/boxdata/agents/";

	public static final int FAIL_LIMIT = 3;
	public static Map<String, Integer> failList = new HashMap<String, Integer>();

	public abstract boolean download(String remoteFile, String downloadedPath, int server);

	public abstract void setShowProgressWindow(boolean show);

	public static Downloader createDownloader() {
		if (Settings.getConnectionType() == Settings.FTP_CONNECTION) {
			Downloader downloader = FtpDownloader.getInstance();
			return downloader;
		} else {
			Downloader downloader = new HttpDownloader();
			return downloader;
		}
	}

	public static String getHttpAddress(String ftpPath, int server) {
		String rootPath = null;
		switch (server) {
		case 0:
			rootPath = HTTP_SERVER_ROOT_0;
			break;
		case 1:
			rootPath = HTTP_SERVER_ROOT_1;
			break;
		case 2:
			rootPath = HTTP_SERVER_ROOT_2;
			break;
		case 3:
			rootPath = HTTP_SERVER_ROOT_3;
			break;
		default:
			return ftpPath;
		}
		return rootPath + ftpPath;
	}

	public static void manageFailureList(String httpPath, boolean success) {
		if (success) {
			failList.remove(httpPath);
		} else {
			if (failList.get(httpPath) == null) {
				failList.put(httpPath, 1);
			} else {
				Integer failCount = failList.get(httpPath);
				failCount++;
				failList.put(httpPath, failCount);

				// TODO send a notification if the fail count reachs the fail
				// limit
				if (failCount == FAIL_LIMIT) {
					System.out.println("fail limit reached");
				}
			}
		}
	}

	/*
	 * @param httpPath the http path of the file that needs to be downloaded
	 * 
	 * @return boolean if failure limit is not exceeded, return true, false
	 * otherwise
	 */
	public static boolean shouldDownload(String httpPath) {
		if (failList.get(httpPath) == null || failList.get(httpPath) < FAIL_LIMIT) {
			return true;
		} else {
			return false;
		}
	}
}
